package cn.echo.ecc.service.impl;

import cn.echo.ecc.constants.ImmutableCommon;
import cn.echo.ecc.domain.Blacklist;
import cn.echo.ecc.enums.GlobalExceptionCode;
import cn.echo.ecc.mapper.BlacklistMapper;
import cn.echo.ecc.service.IBlacklistService;
import cn.echo.ecc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulan
 * @since 2022-10-04
 */
@Service
public class BlacklistServiceImpl extends ServiceImpl<BlacklistMapper, Blacklist> implements IBlacklistService {

    @Override
    @CacheEvict(cacheNames = ImmutableCommon.REDIS_BLACKLIST_CACHE_CACHENAME,key = ImmutableCommon.REDIS_BLACKLIST_CACHE_KEY)
    public boolean insert(Blacklist blacklist) {
        String phone = blacklist.getPhone();
        AssertUtil.isPhone(phone, GlobalExceptionCode.PHONE_FORMAT_ERROR);
        Blacklist blacklist1 = getBlacklist(phone);
        AssertUtil.isNull(blacklist1, GlobalExceptionCode.BLACKLIST_EXISTED_ERROR);
        return super.insert(blacklist);
    }

    @Override
    @Cacheable(cacheNames = ImmutableCommon.REDIS_BLACKLIST_CACHE_CACHENAME,key = ImmutableCommon.REDIS_BLACKLIST_CACHE_KEY)
    public List<Blacklist> getBlacklist() {
        return selectList(null);
    }

    @Override
    @CacheEvict(cacheNames = ImmutableCommon.REDIS_BLACKLIST_CACHE_CACHENAME,key = ImmutableCommon.REDIS_BLACKLIST_CACHE_KEY)
    public boolean updateById(Blacklist entity) {
        return super.updateById(entity);
    }

    @Override
    @CacheEvict(cacheNames = ImmutableCommon.REDIS_BLACKLIST_CACHE_CACHENAME,key = ImmutableCommon.REDIS_BLACKLIST_CACHE_KEY)
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    private Blacklist getBlacklist(String phone) {
        Wrapper<Blacklist> wrapper = new EntityWrapper<>();
        wrapper.eq("phone",phone);
        return selectOne(wrapper);
    }
}
